/**
 * 保存数据到localStorage
 * @param {string} key 存储键
 * @param {any} data 要存储的数据
 */
export function saveToLocalStorage(key, data) {
  try {
    const jsonString = JSON.stringify(data)
    localStorage.setItem(key, jsonString)
    return true
  } catch (error) {
    console.error('保存到localStorage失败:', error)
    return false
  }
}

/**
 * 从localStorage加载数据
 * @param {string} key 存储键
 * @returns {any} 解析后的数据，失败时返回null
 */
export function loadFromLocalStorage(key) {
  try {
    const jsonString = localStorage.getItem(key)
    if (jsonString === null) {
      return null
    }
    return JSON.parse(jsonString)
  } catch (error) {
    console.error('从localStorage加载失败:', error)
    return null
  }
}

/**
 * 从localStorage删除数据
 * @param {string} key 存储键
 */
export function removeFromLocalStorage(key) {
  try {
    localStorage.removeItem(key)
    return true
  } catch (error) {
    console.error('从localStorage删除失败:', error)
    return false
  }
}

/**
 * 清空localStorage
 */
export function clearLocalStorage() {
  try {
    localStorage.clear()
    return true
  } catch (error) {
    console.error('清空localStorage失败:', error)
    return false
  }
}